﻿using ProjectCloth.Entity;
using ProjectCloth.Entity.Enum;
using ProjectCloth.FrmUI.Common;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ProjectCloth.FrmUI
{
    public partial class SaleOrderShow : Form
    {
        private ClothContext db = new ClothContext();
        private List<Entity.Product> productList = new List<Entity.Product>();
        private int _size = 0;
        private string prefix = "J";
        private bool isSearch = false;
        private string _orderNo = "";
        public SaleOrderShow(int size)
        {
            Init(size);
        }
        public SaleOrderShow(string orderNo)
        {
            LoadSaleOrder(orderNo);
        }
        public void LoadSaleOrder(string orderNo)
        {
            InitializeComponent();
            littlecountTxt.Visible = false;
            littlecountlab.Visible = false;
            var order = db.SaleOrders.AsNoTracking().Where(o => o.OrderNo == orderNo).FirstOrDefault();
            if (order == null) return;

            isSearch = true;
            _orderNo = orderNo;
            


            DataGridViewComboBoxColumn GenderColumn = Unit as DataGridViewComboBoxColumn;
            GenderColumn.Items.Add("米");
            GenderColumn.Items.Add("码");
            if (orderNo.Contains("D"))
            {
                prefix = "D";
                orderTypeLab.Text = "大货单";
            }

            productList = db.Products.ToList();
            #region 表  头部/底部
            orderNoTxt.Text = order.OrderNo;
            makerCbx.DataSource = db.Users.Where(o => o.Enabled == true).ToList();
            makerCbx.DisplayMember = "Name";
            makerCbx.ValueMember = "Id";
            makerCbx.SelectedValue = order.MakerId;
            createTimePick.Value = order.CreateTime;
            inmoneyTime.Value = order.InMoneyDate;
            summaryTxt.Text = order.Summary;
            RemarkTxt.Text = order.Remark;
            customerTxt.Text = order.CustomerName;

            inmoneycbb.DataSource = db.CashAccounts.ToList();
            inmoneycbb.DisplayMember = "TradeTypeName";
            inmoneycbb.ValueMember = "Id";
            if (order.InMoneyAccountId != null && order.InMoneyAccountId > 0)
                inmoneycbb.SelectedValue = order.InMoneyAccountId;
            else inmoneycbb.SelectedValue = 0;

            inmoneyAmountTxt.Text = order.InMoneyAmount.ToString();
            preferentialTxt.Text = order.Preferential.ToString();

            CompanyNameTxt.Text = order.CompanyName;
            PhoneTxt.Text = order.Phone;
            LiaisonTxt.Text = order.Liaison;

            #endregion
            dataGridView1.Columns["ProductNo"].Visible = false;
            dataGridView1.Columns["ProductCode"].Visible = true;
            dataGridView1.Columns["ProductCode"].DisplayIndex = 0;
            dataGridView1.Columns["OrderItemStatus"].Visible = true;
            dataGridView1.Columns["OrderItemId"].Visible = false;
            var itemsSource = from o in db.SaleOrderItems.AsNoTracking().Where(o => o.OrderId == order.Id).ToList()
                              join p in db.Products.ToList() on o.ProductId equals p.Id
                              select new
                              {
                                  ProductCode = p.ProductNo,
                                  ProductName = p.Name,
                                  ColorType = o.ColorType,
                                  Unit = EnumDefine.GetEnumDescription((Unit)o.Unit),
                                  o.Price,
                                  o.Quantity,
                                  Sum = o.Amount,
                                  o.Remark,
                                  OrderItemStatus = EnumDefine.GetEnumDescription((ItemStatus)o.OrderItemStatus),
                                  OrderItemId = o.Id
                              };
            dataGridView1.Refresh();
            dataGridView1.DataSource = itemsSource.ToList();

        }
        public void Init(int size)
        {
            InitializeComponent();
            DataGridViewComboBoxColumn GenderColumn = Unit as DataGridViewComboBoxColumn;
            GenderColumn.Items.Add("米");
            GenderColumn.Items.Add("码");

            if (size == 1)
            {
                prefix = "D";
                _size = size;
                orderTypeLab.Text = "大货单";
                GenderColumn.DefaultCellStyle.NullValue = "码";
            }
            else
                GenderColumn.DefaultCellStyle.NullValue = "米";
            db = new ClothContext();
            productList = db.Products.ToList();
            makerCbx.DataSource = db.Users.Where(o => o.Enabled == true).ToList();
            makerCbx.DisplayMember = "Name";
            makerCbx.ValueMember = "Id";

            inmoneycbb.DataSource = db.CashAccounts.ToList();
            inmoneycbb.DisplayMember = "TradeTypeName";
            inmoneycbb.ValueMember = "Id";
            inmoneycbb.SelectedValue = 0;

           
            //DataGridViewComboEditBoxColumn cbb = dataGridView1.Columns["ProductNo"] as DataGridViewComboEditBoxColumn;
            //if (cbb != null)
            //{
            //    cbb.DefaultCellStyle.NullValue = "";// lbType.Text;//显示默认值 根据自己的需求改
            //    cbb.DataPropertyName = "";
            //    cbb.ValueMember = "Id";
            //    cbb.DisplayMember = "ProductNo";
            //    cbb.DataSource = productList;
            //}
            var count = db.SaleOrders.Count() + 1;
            var countNo = count.ToString().PadLeft(3, '0');
            var preNo = prefix + "-" + DateTime.Now.Date.ToString("yyyyMMdd") + "-" + countNo;
            while (true)
            {
                if (db.SaleOrders.Where(o => o.OrderNo == preNo).Count() > 0)
                {
                    count++;
                    countNo = count.ToString().PadLeft(3, '0');
                    preNo = prefix + DateTime.Now.Date.ToString("yyyyMMdd") + countNo;
                }
                else
                {
                    break;
                }
            }
            var date = createTimePick.Value;
            orderNoTxt.Text = preNo;
            GetOrderRemarkNo();
        }
      
       
       
        /// <summary>
        /// 加载销售单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void refreshBtn_Click(object sender, EventArgs e)
        {
            LoadSaleOrder(_orderNo);
        }

        private void inmoneyAmountTxt_TextChanged(object sender, EventArgs e)
        {
            changeFinal();
        }
        private void preferentialTxt_TextChanged(object sender, EventArgs e)
        {
            //changeFinal();
        }
        /// <summary>
        /// 修改优惠后金额
        /// </summary>
        private void changeFinal()
        {
            try
            {


                if (string.IsNullOrEmpty(preferentialTxt.Text) || preferentialTxt.Text == "0" || preferentialTxt.Text == "0.00")
                {
                    finalMoneyTxt.Text = inmoneyAmountTxt.Text;
                }
                else
                {
                    if (string.IsNullOrEmpty(inmoneyAmountTxt.Text) || inmoneyAmountTxt.Text == "")
                    {
                        finalMoneyTxt.Text = "0";
                        preferentialTxt.Text = "0";
                    }
                    else
                    {
                        var amount = Convert.ToDecimal(inmoneyAmountTxt.Text) - Convert.ToDecimal(preferentialTxt.Text);
                        finalMoneyTxt.Text = amount.ToString();
                    }

                }
            }
            catch (Exception e)
            {
                MessageBox.Show("出现错误！，" + e.ToString());
            }
        }

        private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex == 0)
            {
                var form = new ProductSelectFrm();
                var result = form.ShowDialog();
                dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = form.productNo;
            }
        }

        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridView1.CurrentRow.Cells["ColorType"].Selected == true && dataGridView1.CurrentRow.Cells["ColorType"].Value != null)
            {
                string txt = dataGridView1.CurrentRow.Cells["ColorType"].Value.ToString();
                dataGridView1.CurrentRow.Cells["ColorType"].Value = txt + "#";
            }
            if (dataGridView1.CurrentRow.Cells["Quantity"].Selected == true && dataGridView1.CurrentRow.Cells["Quantity"].Value != null)
            {
                dataGridView1.CurrentRow.Cells["Sum"].Value =
                                      Convert.ToDecimal(dataGridView1.CurrentRow.Cells["Price"].Value) * Convert.ToDecimal(dataGridView1.CurrentRow.Cells["Quantity"].Value);//计算金额
                decimal paysum = 0;
                decimal quantity = 0;
                for (int i = 0; i < dataGridView1.RowCount - 1; i++)
                {
                    paysum += Convert.ToDecimal(dataGridView1.Rows[i].Cells["Sum"].Value);
                    quantity += Convert.ToDecimal(dataGridView1.Rows[i].Cells["Quantity"].Value);
                }
                littlecountTxt.Text = quantity.ToString();
                inmoneyAmountTxt.Text = paysum.ToString();
            }
        }
        private string GetOrderRemarkNo()
        {
            try
            {
                if (_size == 0)//剪版
                {
                    var text = db.SaleOrders.Where(o => o.OrderNo.Contains("J") && o.Status != (int)Status.Cancel).OrderByDescending(o => o.CreateTime).Select(o => o.Remark).FirstOrDefault();
                    if (text != null)
                    {
                        var list = text.Split('-');
                        if (list.Count() == 3 && list[2] != null)
                        {
                            int no = Convert.ToInt32(list[2]);
                            no += 1;
                            RemarkTxt.Text = list[0] + "-" + list[1] + "-" + no.ToString().PadLeft(4, '0');

                        }
                    }

                }
                else//大货
                {
                    var text = db.SaleOrders.Where(o => o.OrderNo.Contains("D") && o.Status != (int)Status.Cancel).OrderByDescending(o => o.CreateTime).Select(o => o.Remark).FirstOrDefault();
                    if (text != null)
                    {
                        var list = text.Split('-');
                        if (list.Count() == 3 && list[2] != null)
                        {
                            int no = Convert.ToInt32(list[2]);
                            no += 1;
                            RemarkTxt.Text = list[0] + "-" + list[1] + "-" + no.ToString().PadLeft(4, '0');
                        }
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("出现错误！");
            }
            return "";
        }

        private void preferentialTxt_Leave(object sender, EventArgs e)
        {
            changeFinal();
        }

        private void dataGridView1_CurrentCellChanged(object sender, EventArgs e)
        {

        }

        private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {


        }

        private void dataGridView1_MouseLeave(object sender, EventArgs e)
        {

        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }
    }
}
